//
//  MTSetSexVC.m
//  met
//
//  Created by 李晓俊 on 2019/5/8.
//  Copyright © 2019 李晓俊. All rights reserved.
//

#import "MTSetSexVC.h"
#import "MTShouQuanVC.h"
#import <RSKImageCropper/RSKImageCropper.h>
#import "YYImageClipViewController.h"
@interface MTSetSexVC ()<
UINavigationControllerDelegate,
UIImagePickerControllerDelegate,
UIActionSheetDelegate,
YYImageClipDelegate,RSKImageCropViewControllerDelegate
>
@property (weak, nonatomic) IBOutlet UIButton *goBut;
@property (weak, nonatomic) IBOutlet UIButton *manBut;
@property (weak, nonatomic) IBOutlet UIButton *womanBut;
@property (weak, nonatomic) IBOutlet UITextField *nickname;

@property (weak, nonatomic) IBOutlet NSLayoutConstraint *height;

@property (nonatomic,strong)  NSString *sex;
@property (weak, nonatomic) IBOutlet UIImageView *headImage;

@property (nonatomic,strong) NSString *porId;
@property (nonatomic,strong) NSString *porUrl;

@property (nonatomic,strong) NSString *manporId;
@property (nonatomic,strong) NSString *manporUrl;
@property (nonatomic,strong) NSString *womanporId;
@property (nonatomic,strong) NSString *womanporUrl;

@property (nonatomic,strong) NSString *imgDone;
@property (nonatomic,strong) UIImage *imgChoose;

@end

@implementation MTSetSexVC

- (void)viewDidLoad {
    [super viewDidLoad];

    self.goBut.layer.borderWidth = 2;
    self.goBut.layer.borderColor = KBlackColor.CGColor;
    self.height.constant = 20 + BottomHeight;
    self.goBut.backgroundColor = HEXCOLOR(0xCDD3DB);
    
    self.headImage.userInteractionEnabled = YES;
    UITapGestureRecognizer *back = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(chooseClick)];
    [self.headImage addGestureRecognizer:back];
    
    //默认
    self.sex = @"";
    self.goBut.backgroundColor = HEXCOLOR(0xCDD3DB);
    self.goBut.userInteractionEnabled = NO;
    
    self.imgDone = @"";
    
    //初始化
//    [self getManImage];
//    [self getwoManImage];

}
//选择头像
- (void)chooseClick {
//    if (self.sex.length == 0) {
//        [self.view maketishiToast:@"请先选择性别"];
//        return;
//    }
    UIActionSheet *choiceSheet = [[UIActionSheet alloc] initWithTitle:nil
                                                             delegate:self
                                                    cancelButtonTitle:@"取消"
                                               destructiveButtonTitle:nil
                                                    otherButtonTitles:@"拍照", @"从相册中选取", nil];
    [choiceSheet showInView:self.view];
    
    
//    MTChoosePortraitVC *vc = [[MTChoosePortraitVC alloc] init];
//    vc.sex = self.sex;
//    vc.choosImage = ^(PortraitModel * md) {
//        NSString *sexImage = @"";
//        if ([self.sex isEqualToString:@"1"]) {
//            sexImage = @"男（未选中）";
//        }else {
//            sexImage = @"女（未选中）";
//        }
//        self.porUrl = md.portraitUrl;
//        self.porId = md.portraitId;
//        [self.headImage sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@",md.portraitUrl]] placeholderImage:[UIImage imageNamed:sexImage]];
//    };
//    [self.navigationController pushViewController:vc animated:YES];
}
- (IBAction)nextClick:(id)sender {
//    if (self.nickname.text.length == 0) {
//        [self.view maketishiToast:@"请先输入昵称"];
//        return;
//    }
//    if (self.sex.length == 0) {
//        [self.view maketishiToast:@"请先选择性别"];
//        return;
//    }
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    AccountService *acc = [AccountService getObject];
    acc.httpRequestResultBlock = ^(id data,int code){
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        if (code == 1) {
            [self getUserInfo];
        }else {
            [self.view maketishiToast:data];
        }
    };
    if ([self.imgDone isEqualToString:@"1"]) {
        [acc updUsersInfo:self.porId nickName:self.nickname.text sex:self.sex portraitMap:self.imgChoose];
    }else {
        if (  [self.sex isEqualToString:@"1"]) {
            //男
            [acc updUsersInfo:self.porId nickName:self.nickname.text sex:self.sex portraitMap:[UIImage imageNamed:@"男（选中） 拷贝"]];

        }else {
            [acc updUsersInfo:self.porId nickName:self.nickname.text sex:self.sex portraitMap:[UIImage imageNamed:@"女（选中）2"]];
        }
    }
}
- (void)getUserInfo{
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    AccountService *acc = [AccountService getObject];
    acc.httpRequestResultBlock = ^(id data,int code){
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        if (code == 1) {
            KUSER = data;
            NSUserDefaults *userInfo = [NSUserDefaults standardUserDefaults];
            NSDictionary *dic = [KUSER mj_keyValues];
            //             操作者将包含用户信息的数组arr持久化
            [userInfo setValue:dic forKey:@"userinfo"];
            //把值立即存进去,放置数据丢失
            [[NSUserDefaults standardUserDefaults]synchronize];
            
            MTShouQuanVC *vc = GetViewControllerInStoryboard(@"Login", @"MTShouQuanVC");
            [self.navigationController pushViewController:vc animated:YES];
        }else {
            [self.view maketishiToast:data];
        }
    };
    [acc findUserInfo];
}
- (IBAction)sexClick:(UIButton *)sender {
    self.sex = @"1";
    self.manBut.selected = YES;
    self.womanBut.selected = NO;
    self.goBut.backgroundColor =  HEXCOLOR(0xFEF45C);
    self.goBut.userInteractionEnabled = YES;
    
//    self.porId = self.manporId;
//    self.porUrl = self.manporUrl;
    if ([self.imgDone isEqualToString:@"1"]) {
        self.headImage.image = self.imgChoose;
    }else {
        self.headImage.image = [UIImage imageNamed:@"男（选中） 拷贝"];
    }
//    [self.headImage sd_setImageWithURL:[NSURL URLWithString:self.porUrl] placeholderImage:[UIImage imageNamed:@"男（选中） 拷贝"]];
}
- (IBAction)womanClcik:(id)sender {
    self.sex = @"0";
    self.manBut.selected = NO;
    self.womanBut.selected = YES;
    self.goBut.backgroundColor =  HEXCOLOR(0xFEF45C);
    self.goBut.userInteractionEnabled = YES;
    
//    self.porId = self.womanporId;
//    self.porUrl = self.womanporUrl;
//    [self.headImage sd_setImageWithURL:[NSURL URLWithString:self.porUrl] placeholderImage:[UIImage imageNamed:@"女（选中）"]];
    if ([self.imgDone isEqualToString:@"1"]) {
        self.headImage.image = self.imgChoose;
    }else {
        self.headImage.image = [UIImage imageNamed:@"女（选中）2"];
    }
}


#pragma mark UIActionSheetDelegate
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex {
    if (buttonIndex == 0) {
        // 拍照
        if ([self isCameraAvailable] && [self doesCameraSupportTakingPhotos]) {
            UIImagePickerController *controller = [[UIImagePickerController alloc] init];
            controller.sourceType = UIImagePickerControllerSourceTypeCamera;
            if ([self isFrontCameraAvailable]) {
                controller.cameraDevice = UIImagePickerControllerCameraDeviceRear;
            }
            NSMutableArray *mediaTypes = [[NSMutableArray alloc] init];
            [mediaTypes addObject:(__bridge NSString *)kUTTypeImage];
            controller.mediaTypes = mediaTypes;
            controller.delegate = self;
            [self presentViewController:controller
                               animated:YES
                             completion:^(void){
                                 NSLog(@"Picker View Controller is presented");
                             }];
        }
        
    } else if (buttonIndex == 1) {
        // 从相册中选取
        if ([self isPhotoLibraryAvailable]) {
            UIImagePickerController *controller = [[UIImagePickerController alloc] init];
            controller.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
            NSMutableArray *mediaTypes = [[NSMutableArray alloc] init];
            [mediaTypes addObject:(__bridge NSString *)kUTTypeImage];
            controller.mediaTypes = mediaTypes;
            controller.delegate = self;
            [self presentViewController:controller
                               animated:YES
                             completion:^(void){
                                 NSLog(@"Picker View Controller is presented");
                             }];
        }
    }
}

#pragma mark - UIImagePickerController Delegate
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    UIImage *portraitImg = [info objectForKey:@"UIImagePickerControllerOriginalImage"];
    
    
    RSKImageCropViewController *imageCropVC = [[RSKImageCropViewController alloc] initWithImage:portraitImg cropMode:RSKImageCropModeSquare];
    imageCropVC.delegate = self;
    [picker pushViewController:imageCropVC animated:NO];
    
//    YYImageClipViewController *imgCropperVC = [[YYImageClipViewController alloc] initWithImage:portraitImg cropFrame:CGRectMake(0, 100.0f, self.view.frame.size.width, self.view.frame.size.width) limitScaleRatio:3.0];
//    imgCropperVC.delegate = self;
//    [picker pushViewController:imgCropperVC animated:NO];
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
    [picker dismissViewControllerAnimated:YES completion:nil];
}

- (void)imageCropViewControllerDidCancelCrop:(RSKImageCropViewController *)controller
{
    [controller dismissViewControllerAnimated:YES completion:nil];
}

// The original image has been cropped. Additionally provides a rotation angle used to produce image.
- (void)imageCropViewController:(RSKImageCropViewController *)controller
                   didCropImage:(UIImage *)croppedImage
                  usingCropRect:(CGRect)cropRect
                  rotationAngle:(CGFloat)rotationAngle
{
    
    self.imgChoose = croppedImage;
    self.imgDone = @"1";
    self.headImage.image = self.imgChoose;
    [controller dismissViewControllerAnimated:YES completion:nil];
    
}

// The original image will be cropped.
- (void)imageCropViewController:(RSKImageCropViewController *)controller
                  willCropImage:(UIImage *)originalImage
{
    // Use when `applyMaskToCroppedImage` set to YES.
}




#pragma mark - YYImageCropperDelegate
- (void)imageCropper:(YYImageClipViewController *)cropperViewController didFinished:(UIImage *)editedImage {
    self.imgChoose = editedImage;
    self.imgDone = @"1";
    self.headImage.image = self.imgChoose;
    [cropperViewController dismissViewControllerAnimated:YES completion:nil];
}

- (void)imageCropperDidCancel:(YYImageClipViewController *)cropperViewController {
    [cropperViewController dismissViewControllerAnimated:YES completion:nil];
}

#pragma mark - image scale utility
- (UIImage *)imageByScalingToMaxSize:(UIImage *)sourceImage {
    if (sourceImage.size.width < kScreenWidth) return sourceImage;
    CGFloat btWidth = 0.0f;
    CGFloat btHeight = 0.0f;
    if (sourceImage.size.width > sourceImage.size.height) {
        btHeight = kScreenWidth;
        btWidth = sourceImage.size.width * (kScreenWidth / sourceImage.size.height);
    } else {
        btWidth = kScreenWidth;
        btHeight = sourceImage.size.height * (kScreenWidth / sourceImage.size.width);
    }
    CGSize targetSize = CGSizeMake(btWidth, btHeight);
    return [self imageByScalingAndCroppingForSourceImage:sourceImage targetSize:targetSize];
}

- (UIImage *)imageByScalingAndCroppingForSourceImage:(UIImage *)sourceImage targetSize:(CGSize)targetSize {
    UIImage *newImage = nil;
    CGSize imageSize = sourceImage.size;
    CGFloat width = imageSize.width;
    CGFloat height = imageSize.height;
    CGFloat targetWidth = targetSize.width;
    CGFloat targetHeight = targetSize.height;
    CGFloat scaleFactor = 0.0;
    CGFloat scaledWidth = targetWidth;
    CGFloat scaledHeight = targetHeight;
    CGPoint thumbnailPoint = CGPointMake(0.0,0.0);
    if (CGSizeEqualToSize(imageSize, targetSize) == NO)
    {
        CGFloat widthFactor = targetWidth / width;
        CGFloat heightFactor = targetHeight / height;
        
        if (widthFactor > heightFactor)
            scaleFactor = widthFactor; // scale to fit height
        else
            scaleFactor = heightFactor; // scale to fit width
        scaledWidth  = width * scaleFactor;
        scaledHeight = height * scaleFactor;
        
        // center the image
        if (widthFactor > heightFactor)
        {
            thumbnailPoint.y = (targetHeight - scaledHeight) * 0.5;
        }
        else
            if (widthFactor < heightFactor)
            {
                thumbnailPoint.x = (targetWidth - scaledWidth) * 0.5;
            }
    }
    UIGraphicsBeginImageContext(targetSize); // this will crop
    CGRect thumbnailRect = CGRectZero;
    thumbnailRect.origin = thumbnailPoint;
    thumbnailRect.size.width  = scaledWidth;
    thumbnailRect.size.height = scaledHeight;
    
    [sourceImage drawInRect:thumbnailRect];
    
    newImage = UIGraphicsGetImageFromCurrentImageContext();
    if(newImage == nil) NSLog(@"could not scale image");
    
    //pop the context to get back to the default
    UIGraphicsEndImageContext();
    return newImage;
}

#pragma mark - UINavigationControllerDelegate
- (void)navigationController:(UINavigationController *)navigationController willShowViewController:(UIViewController *)viewController animated:(BOOL)animated {
}

- (void)navigationController:(UINavigationController *)navigationController didShowViewController:(UIViewController *)viewController animated:(BOOL)animated {
    
}

#pragma mark - camera utility
- (BOOL)isCameraAvailable {
    return [UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera];
}

- (BOOL)isRearCameraAvailable {
    return [UIImagePickerController isCameraDeviceAvailable:UIImagePickerControllerCameraDeviceRear];
}

- (BOOL)isFrontCameraAvailable {
    return [UIImagePickerController isCameraDeviceAvailable:UIImagePickerControllerCameraDeviceFront];
}

- (BOOL)doesCameraSupportTakingPhotos {
    return [self cameraSupportsMedia:(__bridge NSString *)kUTTypeImage sourceType:UIImagePickerControllerSourceTypeCamera];
}

- (BOOL)isPhotoLibraryAvailable {
    return [UIImagePickerController isSourceTypeAvailable:
            UIImagePickerControllerSourceTypePhotoLibrary];
}

- (BOOL)canUserPickVideosFromPhotoLibrary {
    return [self
            cameraSupportsMedia:(__bridge NSString *)kUTTypeMovie sourceType:UIImagePickerControllerSourceTypePhotoLibrary];
}

- (BOOL)canUserPickPhotosFromPhotoLibrary {
    return [self
            cameraSupportsMedia:(__bridge NSString *)kUTTypeImage sourceType:UIImagePickerControllerSourceTypePhotoLibrary];
}

- (BOOL)cameraSupportsMedia:(NSString *)paramMediaType sourceType:(UIImagePickerControllerSourceType)paramSourceType {
    __block BOOL result = NO;
    if ([paramMediaType length] == 0) {
        return NO;
    }
    NSArray *availableMediaTypes = [UIImagePickerController availableMediaTypesForSourceType:paramSourceType];
    [availableMediaTypes enumerateObjectsUsingBlock: ^(id obj, NSUInteger idx, BOOL *stop) {
        NSString *mediaType = (NSString *)obj;
        if ([mediaType isEqualToString:paramMediaType]){
            result = YES;
            *stop= YES;
        }
    }];
    return result;
}
@end
